package com.example.dingtalkwebproject.controller;

import com.example.dingtalkwebproject.exception.BusinessException;
import com.example.dingtalkwebproject.pojo.*;
import com.example.dingtalkwebproject.pojo.vo.procorementInfoVO;
import com.example.dingtalkwebproject.pojo.vo.rejectReportedVO;
import com.example.dingtalkwebproject.service.*;
import com.example.dingtalkwebproject.utils.AjaxResult;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/reported")
public class getReportedController {

    @Autowired
    private procorementInfoVOService procorementInfoVOService;
    @Autowired
    private wBlShipHdService wBlShipHdService;
    @Autowired
    private dArcStaffService dArcStaffService;
    @Autowired
    private dingTalkMessageQueueService dingTalkMessageQueueService;
    @Autowired
    private CWeiXinConfigQyService cWeiXinConfigQyService;
    private static final String defectiveJpg = "https://newerp.mumuso.com/uploadfile/W_BL_SHIP_HD_VIDEO/wlcc.JPG";
    private static final String noticeDingTalkChatId = "CHAT01B7A8792EF82AB271E1B23EFC8ACAC5";
    private static final String operateDingTalkChatId = "CHATE078CD83A9BEEAA8B6E37E5D719436D6";

    @Autowired
    private dingTalkSendContentService dingTalkSendContentService;
    @Autowired
    private VideoStorageService videoStorageService;
    @Autowired
    private StoredProceduresService storedProceduresService;
    @Autowired
    private sysLoginUserService sysLoginUserService;


    @GetMapping("/getReportedInfo/{billId}")
    public AjaxResult getReportedInfoByObject(@PathVariable String billId) {
        if (StringUtils.isBlank(billId)) {
            return AjaxResult.error("当前参数未被定义!");
        }
        procorementInfoVO procorementInfoVO = procorementInfoVOService.selectDefectiveInfoByBillId(billId);
        if (ObjectUtils.isEmpty(procorementInfoVO)) {
            return AjaxResult.error("未获取到当前提报的残次单号!");
        }
        return AjaxResult.success(procorementInfoVO);
    }


    /**
     * 拒绝提报
     * 区域经理驳回
     *
     * @param rejectReportedVO
     * @return
     */
    @PostMapping("/rejectReported")
    public AjaxResult rejectReportedByBillId(@RequestBody rejectReportedVO rejectReportedVO) {
        if (StringUtils.isEmpty(rejectReportedVO.getBillId())) {
            return AjaxResult.error("残次单号不能为空!");
        }

        if (StringUtils.isBlank(rejectReportedVO.getRejectReason())) {
            return AjaxResult.error("残次驳回原因不能为空!");
        }

        // 获取当前残次单状态
        try {
            // 2. 获取单据信息
            wBlShipHd shipHd = wBlShipHdService.selectShipInfoByBillId(rejectReportedVO.getBillId());
            if (shipHd == null) {
                return AjaxResult.error(" 残次单【" + rejectReportedVO.getBillId() + "】不存在");
            }

            if ("004".equals(shipHd.getStatus())) {
                return AjaxResult.error("当前残次单号【" + rejectReportedVO.getBillId() + "】已经完成终审操作，不可进行驳回!");
            }
            // 3. 状态机校验
            String currentStatus = shipHd.getShStatus();
            switch (currentStatus) {
                case "999":
                    return AjaxResult.error(" 残次单【" + rejectReportedVO.getBillId() + "】已终止，不可再进行驳回操作!");
                case "000":
                    return AjaxResult.error(" 残次单【" + rejectReportedVO.getBillId() + "】待确认，不可直接进行驳回操作!");
                case "002":
                    return AjaxResult.error("当前残次单【" + rejectReportedVO.getBillId() + "】已经被你审核通过，你不可以再驳回!");
                case "001":
                    // 正常流程继续执行
                    break;
                default:
                    return AjaxResult.error(" 残次单【" + rejectReportedVO.getBillId() + "】状态异常");
            }
            // 4. 执行审批
            int updated = wBlShipHdService.updateShipHdByBillId(rejectReportedVO);

            if (updated > 0) {
                // 驳回之后发送信息给到门店
                // 区域经理驳回之后将重新提报的链接发送给门店
                sendDingTalkMarkDown(rejectReportedVO, "区域经理驳回");
                return AjaxResult.success(" 残次单【" + rejectReportedVO.getBillId() + "】已经成功驳回!");
            }
            return AjaxResult.error(" 残次单审核操作未生效");
        } catch (Exception e) {
            return AjaxResult.error(" 系统处理异常: " + e.getMessage());
        }
    }


    // 驳回发送信息
    public void sendDingTalkMarkDown(rejectReportedVO reportedVO, String dismissalPerson) {
        // 当前已经被驳回 门店需要重新提报
        CWeiXinConfigQy cobotConfig = getCobotOperateConfig();
        dArcStaff dArcStaff = dArcStaffService.selectDingUserIdByStaffId(reportedVO.getStaffId());


        // 构建Markdown内容（为每个信息项配上更合适的图标）
        StringBuilder markdownBuilder = new StringBuilder()
                .append("### ⚠️ 物流残次商品提报驳回通知\n\n")
                .append("🏬 **门店名称:** ").append(reportedVO.getStoreName()).append("\n")
                .append("📦 **商品名称:** ").append(reportedVO.getItemName()).append("\n")
                .append("👤 **提报人:** ").append(reportedVO.getStaffName()).append("\n")
                .append("👨⚖️ **驳回人:** ").append(dismissalPerson).append("\n\n")  // 关键间隔保留

                .append("❌ **驳回原因:** \n```\n").append(reportedVO.getRejectReason()).append("\n```\n\n")   // 代码块样式优化

                .append("📄 **重新提报:** [点击进入重新提报页面 ➡️](")
                .append("https://mms.mumuso.com:8214/index/#/index/?staffId=")
                .append(reportedVO.getStaffId()).append(")\n\n")   // 链接后单空行

                .append("---\n")
                .append("⏱️ **驳回时间:** ").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).append("\n")
                .append("🔄 **处理状态:** 被驳回（请重新提报）\n\n")  // 状态与提示间单空行

                .append("> 💡 请根据驳回原因修改后重新提报，如有疑问请联系物流部\n")  // 移除多余空行
                .append("> 📎 你也可以通过钉钉工作台中的「残次提报」入口进入重新提报");  // 提示合并

        // 创建消息队列对象
        dingTalkMessageQueue queue = new dingTalkMessageQueue();
        queue.setMsgType("MARKDOWN");
        queue.setTitle("⚠️  物流残次商品提报驳回通知");  // 标题也加上警告图标
        queue.setRobotToken(cobotConfig.getAccessToken());
        queue.setRobotCode(cobotConfig.getAeskey());
        queue.setMarkdownContent(markdownBuilder.toString());
        if (StringUtils.isNotBlank(dArcStaff.getOldStaffId())) {
            queue.setUserIds(dArcStaff.getOldStaffId());   // 指定接收人
        } else {
            queue.setUserIds("475410075935471898");
        }

        // 发送消息
        sendDingTalkMarkdownMessage(queue);
    }

    /**
     * 区域经理审核通过
     *
     * @param requestVO
     * @return
     */
    @PutMapping("/approveReported")
    public AjaxResult approveReportedByBillId(@RequestBody rejectReportedVO requestVO) {
        // 1. 参数校验
        if (StringUtils.isBlank(requestVO.getBillId())) {
            return AjaxResult.error(" 残次单号不能为空");
        }
        try {
            // 2. 获取单据信息
            wBlShipHd shipHd = wBlShipHdService.selectShipInfoByBillId(requestVO.getBillId());
            if (shipHd == null) {
                return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】不存在");
            }

            if ("004".equals(shipHd.getStatus())) {
                return AjaxResult.error("当前物流残次单号【" + requestVO.getBillId() + "】已经完成终审操作，不可进行审核!");
            }
            // 3. 状态机校验
            String currentStatus = shipHd.getShStatus();
            switch (currentStatus) {
                case "002":
                    return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】已审核通过，请勿重复操作");
                case "999":
                    return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】已终止，不可审核");
                case "000":
                    return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】待确认，不可直接审核");
                case "001":
                    // 正常流程继续执行
                    break;
                default:
                    return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】状态异常");
            }
            // 4. 执行审批
            int updated = wBlShipHdService.updateShipHdStatusByBillId(requestVO.getBillId());


            if (updated > 0) {
                // 区域经理审核通过之后将消息发送给门店和采购人员进行审核
                // 根据人员编号获取
                // 区域经理通过之后 将消息发送给提报人和物流审核
                // 获取所有物流人员
                List<sysLoginUser> users = sysLoginUserService.selectAllLogisticsInfos();
                // 将钉钉工号使用逗号隔开
                // 使用Stream API处理
                String staffIds = users.stream()                       // 创建流
                        .map(sysLoginUser::getOldStaffId)                // 提取oldStaffId
                        .filter(id -> id != null && !id.isEmpty())        // 过滤掉null和空字符串
                        .collect(Collectors.joining(","));

                if (StringUtils.isNotBlank(staffIds) && StringUtils.isNotBlank(requestVO.getStaffId())) {
                    // 发送给物流人员
                    // 操作机器人提示
                    CWeiXinConfigQy robotConfig = getCobotOperateConfig();
                    dingTalkMessageQueue queueWl = buildMessageQueueWl(requestVO, robotConfig, staffIds);
                    sendDingTalkMessage(queueWl);

                    // 获取营业员信息
                    dArcStaff dArcStaff = dArcStaffService.selectDingUserIdByStaffId(requestVO.getStaffId());
                    // 通知机器人提示
                    CWeiXinConfigQy config = getCobotConfig();
                    buildMessageQueueWork(requestVO, config, dArcStaff);
                }
                return AjaxResult.success(" 物流残次单【" + requestVO.getBillId() + "】审核通过");
            }
            return AjaxResult.error(" 物流残次单审核操作未生效");
        } catch (Exception e) {
            return AjaxResult.error(" 系统处理异常: " + e.getMessage());
        }
    }


    // 发送钉钉群聊信息
    private void sendDingTalkMessage(rejectReportedVO wBlShipHdVO) {
        // 发送给门店
        CWeiXinConfigQy cobotConfig = getCobotConfig();
        dArcStaff dArcStaff = dArcStaffService.selectDingUserIdByStaffId(wBlShipHdVO.getStaffId());

        StringBuilder title = new StringBuilder()
                .append(wBlShipHdVO.getStoreId()).append("-").append("提报的物流残次").append("--").append(wBlShipHdVO.getItemName());

        // 构建带参数的URL
        String messageUrl = new StringBuilder("https://mms.mumuso.com:8214/index/#/logistics/?")
                .append("billId=").append(wBlShipHdVO.getBillId())
                .append("&staffId=").append(wBlShipHdVO.getStaffId())
                .toString();
        StringBuilder sb = new StringBuilder().append(wBlShipHdVO.getRemark()).append("——").append("区域经理已经审核通过!请点击点击链接进行审核操作!");


        // 直接创建对象并设置属性
        dingTalkMessageQueue queue = new dingTalkMessageQueue();
        queue.setMsgType("LINK");
        queue.setTitle(title.toString());
        queue.setText(sb.toString());
        queue.setRobotCode(cobotConfig.getAeskey());
        queue.setRobotToken(cobotConfig.getAccessToken());
        queue.setMessageUrl(messageUrl);
        queue.setPicUrl(defectiveJpg);
        if (StringUtils.isNotBlank(dArcStaff.getOldStaffId())) {
            queue.setUserIds(dArcStaff.getOldStaffId());
        }
        sendDingTalkMessage(queue);


        // 发送给采购人员
        dingTalkSendContent textContent = new dingTalkSendContent();
        textContent.setTextContent("🚨 物流残次商品提报通知");
        textContent.setChatId(operateDingTalkChatId);
        int inserted = dingTalkSendContentService.insertTextContent(textContent);
        if (inserted > 0) {
            dingTalkSendContent content = new dingTalkSendContent();
            // 使用StringBuilder构建Markdown内容，提高性能
            StringBuilder markdownBuilder = new StringBuilder()
                    .append("### 🚨 物流残次商品提报通知\n\n")
                    .append("🛒 **门店名称:** ").append(wBlShipHdVO.getStoreName()).append("\n\n")
                    .append("👤 **提报人:** ").append(wBlShipHdVO.getStaffName()).append("\n\n")
                    .append("📦 **商品名称:** ").append(wBlShipHdVO.getItemName()).append("\n\n")
                    .append("📦 **商品品类:** ").append(wBlShipHdVO.getClassName()).append("\n\n")
                    .append("📝 **残次描述:** ").append(wBlShipHdVO.getRemark()).append("\n\n")
                    .append("🔗 **审核链接:** [点击进入审核页面 ➡️](https://mms.mumuso.com:8214/index/#/logistics/?billId=")
                    .append(wBlShipHdVO.getBillId()).append(")\n\n")  // 假设有getId()方法获取ID
                    .append("---\n")
                    .append("⏰ **提报时间:** ")
                    .append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).append("\n\n")
                    .append("🔄 **处理状态:** 待审核\n\n")
                    .append("> 💡 请及时处理该物流残次商品提报信息");

            // 设置消息内容
            content.setMarkdownContent(markdownBuilder.toString());
            content.setChatId(operateDingTalkChatId);
            dingTalkSendContentService.insertMarkdownMessage(content);
        }

    }

    private CWeiXinConfigQy getCobotConfig() {
        CWeiXinConfigQy config = cWeiXinConfigQyService.selectRobotInfo();
        if (ObjectUtils.isEmpty(config)) throw new BusinessException("未获取到当前机器人配置信息");
        return config;
    }

    private CWeiXinConfigQy getCobotOperateConfig() {
        CWeiXinConfigQy config = cWeiXinConfigQyService.selectOperationRobotInfo();
        if (ObjectUtils.isEmpty(config)) throw new BusinessException("未获取到当前机器人配置信息");
        return config;
    }

    private void sendDingTalkMessage(dingTalkMessageQueue queue) {
        int result = dingTalkMessageQueueService.sendDingTalkLlnkMessage(queue);
        if (result <= 0) throw new BusinessException("消息发送失败");
    }

    private void sendDingTalkMarkdownMessage(dingTalkMessageQueue queue) {
        int result = dingTalkMessageQueueService.sendDingTalkMarkdownMessage(queue);
        if (result <= 0) throw new BusinessException("消息发送失败");
    }

    private void addStaffIfValid(List<dArcStaff> list, String staffId,
                                 Function<String, dArcStaff> selector) {
        if (StringUtils.isNotBlank(staffId)) {
            dArcStaff staff = selector.apply(staffId);
            if (ObjectUtils.isNotEmpty(staff)) list.add(staff);
        }
    }

    private List<dArcStaff> getRecipientStaffs(rejectReportedVO vo, String type) {
        List<dArcStaff> staffs = new ArrayList<>();
        if ("采购".equals(type)) {
            addStaffIfValid(staffs, vo.getCgStaff(), dArcStaffService::selectDingUserIdByStaffId);
        } else {
            addStaffIfValid(staffs, vo.getStaffId(), dArcStaffService::selectDingUserIdByStaffId);
        }
        return staffs;
    }

    private List<dArcStaff> getRecipientRiskStaffs(rejectReportedVO vo, String type) {
        List<dArcStaff> staffs = new ArrayList<>();
        if (type.equals("通知张元元")) {
            addStaffIfValid(staffs, "MS02901", dArcStaffService::selectDingUserIdByStaffId);
        } else {
            addStaffIfValid(staffs, vo.getStaffId(), dArcStaffService::selectDingUserIdByStaffId);
        }
        return staffs;
    }

    private dingTalkMessageQueue buildMessageQueueWl(rejectReportedVO vo,
                                                     CWeiXinConfigQy config, String staffIds) {
        StringBuilder title = new StringBuilder()
                .append(vo.getStoreId()).append("-").append("提报的物流残次").append("--").append(vo.getItemName());

        StringBuilder sb = new StringBuilder().append(vo.getRemark()).append("——").append("区域经理已经审核通过!待物流人员点击链接进行审核操作!");

        // 构建带参数的URL
        String messageUrl = new StringBuilder("https://mms.mumuso.com:8214/index/#/logistics/?")
                .append("billId=").append(vo.getBillId())
                .append("&staffId=").append(vo.getStaffId())
                .toString();
        // 直接创建对象并设置属性
        dingTalkMessageQueue queue = new dingTalkMessageQueue();
        queue.setMsgType("LINK");
        queue.setTitle(title.toString());
        queue.setText(sb.toString());
        queue.setRobotCode(config.getAeskey());
        queue.setRobotToken(config.getAccessToken());
        queue.setMessageUrl(messageUrl);
        queue.setPicUrl(defectiveJpg);
        queue.setUserIds(staffIds);

        return queue;
    }

    private void buildMessageQueueWork(rejectReportedVO vo,
                                       CWeiXinConfigQy config, dArcStaff staff) {
        StringBuilder title = new StringBuilder()
                .append(vo.getStoreId()).append("-").append("提报的物流残次").append("--").append(vo.getItemName());

        StringBuilder sb = new StringBuilder().append(vo.getRemark()).append("——").append("区域经理已经审核通过!请物流点击链接进行审核操作!");

        // 构建带参数的URL
        String messageUrl = new StringBuilder("https://mms.mumuso.com:8214/index/#/logistics/?")
                .append("billId=").append(vo.getBillId())
                .append("&staffId=").append(staff.getStaffId())
                .toString();
        // 直接创建对象并设置属性
        dingTalkMessageQueue queue = new dingTalkMessageQueue();
        queue.setMsgType("LINK");
        queue.setTitle(title.toString());
        queue.setText(sb.toString());
        queue.setRobotCode(config.getAeskey());
        queue.setRobotToken(config.getAccessToken());
        queue.setMessageUrl(messageUrl);
        queue.setPicUrl(defectiveJpg);
        queue.setUserIds(staff.getOldStaffId());
        sendDingTalkMessage(queue);
    }

    private dingTalkMessageQueue buildMessageQueueCg(rejectReportedVO vo,
                                                     CWeiXinConfigQy config, dArcStaff staff, String type) {
        StringBuilder title = new StringBuilder()
                .append(vo.getStoreId()).append("-").append("提报的物流残次").append("--").append(vo.getItemName());

        // 构建带参数的URL
        String messageUrl = new StringBuilder("https://mms.mumuso.com:8214/index/#/risk/?")
                .append("billId=").append(vo.getBillId())
                .append("&staffId=").append(staff.getStaffId()).append("&type=").append("sendback")
                .toString();
        StringBuilder sb = new StringBuilder();
        if ("updateWl".equals(type)) {
            sb.append(vo.getRemark()).append("——").append("物流已审核,门店已上传物流单号,请风控点击链接进行审核操作!");
        } else if ("tx".equals(type)) {
            sb.append(vo.getRemark()).append("——").append("风控已审核,当前物流残次单已完成!");
        }

        // 直接创建对象并设置属性
        dingTalkMessageQueue queue = new dingTalkMessageQueue();
        queue.setMsgType("LINK");
        queue.setTitle(title.toString());
        queue.setText(sb.toString());
        queue.setRobotToken(config.getAccessToken());
        queue.setRobotCode(config.getAeskey());
        queue.setMessageUrl(messageUrl);
        queue.setPicUrl(defectiveJpg);
        queue.setUserIds(staff.getOldStaffId());

        return queue;
    }

    private dingTalkMessageQueue sendStoreMember(rejectReportedVO vo,
                                                 CWeiXinConfigQy config, dArcStaff staff) {
        StringBuilder title = new StringBuilder()
                .append(vo.getStoreId()).append("-").append("提报的物流残次").append("--").append(vo.getItemName());
        String messageUrl = new StringBuilder("https://mms.mumuso.com:8214/index/#/shoot/?")
                .append("billId=").append(vo.getBillId())
                .append("&staffId=").append(staff.getStaffId())
                .toString();
        // 直接创建对象并设置属性
        dingTalkMessageQueue queue = new dingTalkMessageQueue();
        queue.setMsgType("LINK");
        queue.setTitle(title.toString());
        queue.setText("物流已审核，直接报废，请拍摄报废视频!");
        queue.setRobotToken(config.getAccessToken());
        queue.setRobotCode(config.getAeskey());
        queue.setMessageUrl(messageUrl);
        queue.setPicUrl(defectiveJpg);
        queue.setUserIds(staff.getOldStaffId());

        return queue;
    }


    /**
     * 拒绝提报
     * 采购驳回
     *
     * @param rejectReportedVO
     * @return
     */
    @PostMapping("/procurementRejectReported")
    public AjaxResult procurementRejectReportedByBillId(@RequestBody rejectReportedVO rejectReportedVO) {
        if (StringUtils.isEmpty(rejectReportedVO.getBillId())) {
            return AjaxResult.error("物流残次单号不能为空!");
        }

        if (StringUtils.isBlank(rejectReportedVO.getRejectReason())) {
            return AjaxResult.error("物流残次驳回原因不能为空!");
        }

        // 获取当前残次单状态
        try {
            // 2. 获取单据信息
            wBlShipHd shipHd = wBlShipHdService.selectShipInfoByBillId(rejectReportedVO.getBillId());
            if (shipHd == null) {
                return AjaxResult.error(" 物流残次单【" + rejectReportedVO.getBillId() + "】不存在");
            }

            if ("004".equals(shipHd.getStatus())) {
                return AjaxResult.error("当前物流残次单号【" + rejectReportedVO.getBillId() + "】已经完成终审操作，不可进行驳回!");
            }
            // 3. 状态机校验
            String currentStatus = shipHd.getShStatus();
            switch (currentStatus) {
                case "999":
                    return AjaxResult.error(" 物流残次单【" + rejectReportedVO.getBillId() + "】已终止，不可再进行驳回操作!");
                case "000":
                    return AjaxResult.error(" 物流残次单【" + rejectReportedVO.getBillId() + "】待确认，不可直接进行驳回操作!");
                case "001":
                    return AjaxResult.error("当前物流残次单【" + rejectReportedVO.getBillId() + "】还未被区域经理审核通过，当前流程还不允许你来进行驳回操作!");
                case "002":
                    break;
                default:
                    return AjaxResult.error(" 物流残次单【" + rejectReportedVO.getBillId() + "】状态异常");
            }
            // 4. 执行审批
            int updated = wBlShipHdService.procurementRejectUpdateShipHdByBillId(rejectReportedVO);

            if (updated > 0) {
                sendDingTalkMarkDown(rejectReportedVO, "物流驳回");
                return AjaxResult.success(" 物流残次单【" + rejectReportedVO.getBillId() + "】已经成功驳回!");
            }
            return AjaxResult.error(" 物流残次单审核操作未生效");
        } catch (Exception e) {
            return AjaxResult.error(" 系统处理异常: " + e.getMessage());
        }
    }

    /**
     * 物流审核通过
     *
     * @param requestVO
     * @return
     */
    @PutMapping("/procurementApproveReported")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult procurementApproveReportedByBillId(@RequestBody rejectReportedVO requestVO) {
        // 1. 参数校验
        if (StringUtils.isBlank(requestVO.getBillId())) {
            return AjaxResult.error(" 物流残次单号不能为空");
        }
        try {
            // 2. 获取单据信息
            wBlShipHd shipHd = wBlShipHdService.selectShipInfoByBillId(requestVO.getBillId());
            if (shipHd == null) {
                return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】不存在");
            }


            if ("004".equals(shipHd.getStatus())) {
                return AjaxResult.error("当前物流残次单号【" + requestVO.getBillId() + "】已经完成终审操作，不可进行审核!");
            }
            // 3. 状态机校验
            String currentStatus = shipHd.getShStatus();
            switch (currentStatus) {
                case "999":
                    return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】已终止，不可审核");
                case "000":
                    return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】待确认，不可直接审核");
                case "001":
                    return AjaxResult.error("当前物流残次单【" + requestVO.getBillId() + "】还未被区域经理审核通过，当前流程还不允许你来进行审核操作!");
                case "003":
                    return AjaxResult.error("当前物流残次单【" + requestVO.getBillId() + "】已经被物流审核通过，请勿重复执行审核操作!");
                case "002":
                    break;
                default:
                    return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】状态异常");
            }
            // 4. 执行审批
            int updated = wBlShipHdService.procurementApprovalUpdateShipHdByBillId(requestVO);

            if (updated > 0) {
                // 审批通过之后将物流公司以及付款账户更新

                // 采购审核通过之后发送给风控人员
                // 根据人员编号获取
                // 判断品类
                // 采购审核通过之后发送给风控人员
                // 根据人员编号获取
                CWeiXinConfigQy cobotConfig = getCobotOperateConfig();
                dArcStaff dArcStaff = dArcStaffService.selectDingUserIdByStaffId(requestVO.getStaffId());
                dingTalkMessageQueue queue1 = sendStoreMember(requestVO, cobotConfig, dArcStaff);
                sendDingTalkMessage(queue1);
                return AjaxResult.success(" 物流残次单【" + requestVO.getBillId() + "】审核通过");
            }
            return AjaxResult.error(" 物流残次单审核操作未生效");
        } catch (Exception e) {
            return AjaxResult.error(" 系统处理异常: " + e.getMessage());
        }
    }

    private String storeVideoFile(MultipartFile file) {
        try {
            return videoStorageService.storeVideo(file);
        } catch (IOException e) {
            throw new BusinessException("视频存储失败", e.getMessage());
        }
    }

    // 更新当前残次单的物流单号
    @PutMapping("/submitWlInfo")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateWlInfoByBillId(@RequestPart("data") rejectReportedVO reportedVO,
                                           @RequestPart(value = "file") MultipartFile file) {
        // 参数校验
        if (StringUtils.isAnyBlank(reportedVO.getBillId(), reportedVO.getWlInfoId(), reportedVO.getClassName())) {
            return AjaxResult.error(" 提交失败：残次单号、物流单号和品类均为必填项");
        }
        if (ObjectUtils.isNotEmpty(file)) {
            // 将报废视频上传
            String scrapFileName = storeVideoFile(file);
            reportedVO.setBffj(scrapFileName);
        }
        try {
            // 执行更新操作
            int updated = wBlShipHdService.updateWlBillIdByBillId(reportedVO);
            if (updated > 0) {
                // 更新成功之后通知采购
                // 获取当前机器人信息
                sendMessageToCg(reportedVO);
                // 提醒张元元
                if (StringUtils.isNotBlank(reportedVO.getStaffId()) && StringUtils.isNotBlank(reportedVO.getCgStaff())) {
                    List<dArcStaff> staffs = getRecipientRiskStaffs(reportedVO, "通知张元元");
                    CWeiXinConfigQy robotConfig = getCobotOperateConfig();
                    staffs.forEach(staff -> {
                        dingTalkMessageQueue queue = buildMessageQueueCg(reportedVO, robotConfig, staff, "updateWl");
                        sendDingTalkMessage(queue);
                    });
                }
                return AjaxResult.success(String.format(" 物流残次单【%s】的物流单号提交成功", reportedVO.getBillId()));
            } else {
                return AjaxResult.error(" 提交失败：未找到对应的物流残次单信息");
            }
        } catch (Exception e) {
            return AjaxResult.error(" 系统异常，提交失败，请稍后重试");
        }
    }

    private void sendDingTalkMessageWlBillId(rejectReportedVO wBlShipHdVO) {
        // 1. 基础配置获取
        CWeiXinConfigQy cobotConfig = getCobotOperateConfig();
        dArcStaff dArcStaff = dArcStaffService.selectDingUserIdByStaffId("MS02901");

        // 2. 构建消息标题（突出审核完成状态）
        String title = String.format("%s- 物流残次处理完成（物流单号已更新）", wBlShipHdVO.getStoreId());

        // 3. 消息链接（跳转至带视频的详情页）
        String messageUrl = String.format("https://mms.mumuso.com:8214/index/#/risk/?billId=%s&staffId=%s&type=%s",
                wBlShipHdVO.getBillId(), "MS02901", "sendback");

        // 3. 消息链接（跳转至带视频的详情页）
        String messageUrlCg = String.format("https://mms.mumuso.com:8214/index/#/risk/?billId=%s",
                wBlShipHdVO.getBillId());

        // 4. 核心消息内容构建
        StringBuilder markdownBuilder = new StringBuilder()
                .append("### 🚛 物流残次品物流信息更新\n\n")
                .append("#### **核心信息**\n")
                .append("- 📦 **物流单号:** ").append(wBlShipHdVO.getWlInfoId()).append("\n")
                .append("- 🛒 **门店名称:** ").append(wBlShipHdVO.getStoreName()).append("\n")
                .append("- 👤 **提报人:** ").append(wBlShipHdVO.getStaffName()).append("\n")
                .append("- 📦 **商品名称:** ").append(wBlShipHdVO.getItemName()).append("\n")
                .append("1. 物流审核: 已完成 (").append("你选择的处理方式是寄回供应商，门店已经将物流单号更新").append(")\n")
                .append("2. 门店操作: ").append(wBlShipHdVO.getWlInfoId() != null ? "物流单号已上传" : "需补传物流单号").append("\n\n")
                .append("🔗 **查看详情:** [点击查看完整记录](").append(messageUrlCg).append(")\n\n")
                .append("> 📌 物流单号存档编号: ").append(wBlShipHdVO.getBillId());

        // 5. 发送给门店的链接消息
        dingTalkMessageQueue queue = new dingTalkMessageQueue();
        queue.setMsgType("LINK");
        queue.setTitle(title);
        queue.setText(" 物流审核已完成，门店已上传物流单号！");
        queue.setRobotToken(cobotConfig.getAccessToken());
        queue.setRobotCode(cobotConfig.getAeskey());
        queue.setMessageUrl(messageUrl);
        queue.setPicUrl(defectiveJpg);  // 可替换为视频封面图
        if (StringUtils.isNotBlank(dArcStaff.getOldStaffId())) {
            queue.setUserIds(dArcStaff.getOldStaffId());
        }
        sendDingTalkMessage(queue);

        // 发送给采购人员
        dingTalkSendContent textContent = new dingTalkSendContent();
        textContent.setChatId(noticeDingTalkChatId);
        textContent.setTextContent("🚛 残次品物流信息更新");
        int inserted = dingTalkSendContentService.insertTextContent(textContent);
        // 6. 发送给采购的Markdown通知
        if (inserted > 0) {
            dingTalkSendContent content = new dingTalkSendContent();
            content.setMarkdownContent(markdownBuilder.toString());
            content.setChatId(noticeDingTalkChatId);
            dingTalkSendContentService.insertMarkdownMessage(content);
        }
    }

    public void sendMessageToCg(rejectReportedVO reportedVO) {
        // 当前已经被驳回 门店需要重新提报
        CWeiXinConfigQy cobotConfig = getCobotConfig();
        dArcStaff dArcStaff = dArcStaffService.selectDingUserIdByStaffId(reportedVO.getCgStaff());


        // 构建Markdown内容（为每个信息项配上更合适的图标）
        StringBuilder markdownBuilder = new StringBuilder()
                .append("### ⚠️ 物流残次商品提报物流单号填写完成提醒\n\n")  // 使用警告图标强调驳回状态

                // 门店信息部分
                .append("🏬 **门店名称:** ").append(reportedVO.getStoreName()).append("\n\n")
                .append("📦 **商品名称:** ").append(reportedVO.getItemName()).append("\n\n")
                .append("👤 **提报人:** ").append(reportedVO.getStaffName()).append("\n\n")
                .append("1. 物流审核: 已完成 (").append("你选择的处理方式是寄回供应商，门店已经将物流单号更新").append(")\n")
                .append("2. 门店操作: ").append(reportedVO.getWlInfoId() != null ? "物流单号已上传" : "需补传物流单号").append("\n\n")

                // 驳回原因（使用更醒目的图标）
                .append("❗📦 物流单号: `").append(reportedVO.getWlInfoId()).append("`  ");

        // 创建消息队列对象
        dingTalkMessageQueue queue = new dingTalkMessageQueue();
        queue.setMsgType("MARKDOWN");
        queue.setTitle("⚠️  残次商品提报物流单号填写完成提醒");  // 标题也加上警告图标
        queue.setRobotToken(cobotConfig.getAccessToken());
        queue.setRobotCode(cobotConfig.getAeskey());
        queue.setMarkdownContent(markdownBuilder.toString());
        if (StringUtils.isNotBlank(dArcStaff.getOldStaffId())) {
            queue.setUserIds(dArcStaff.getOldStaffId());   // 指定接收人
        } else {
            queue.setUserIds("475410075935471898");
        }

        // 发送消息
        sendDingTalkMarkdownMessage(queue);
    }


    /**
     * 风控驳回
     *
     * @param rejectReportedVO
     * @return
     */
    @PostMapping("/riskRejectReported")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult riskRejectReportedByBillId(@RequestBody rejectReportedVO rejectReportedVO) {
        if (StringUtils.isEmpty(rejectReportedVO.getBillId())) {
            return AjaxResult.error("物流残次单号不能为空!");
        }

        if (StringUtils.isBlank(rejectReportedVO.getRejectReason())) {
            return AjaxResult.error("物流残次驳回原因不能为空!");
        }

        // 获取当前残次单状态
        try {
            // 2. 获取单据信息
            wBlShipHd shipHd = wBlShipHdService.selectShipInfoByBillId(rejectReportedVO.getBillId());
            if (shipHd == null) {
                return AjaxResult.error(" 物流残次单【" + rejectReportedVO.getBillId() + "】不存在");
            }

            if ("004".equals(shipHd.getStatus())) {
                return AjaxResult.error("当前物流残次单号【" + rejectReportedVO.getBillId() + "】已经完成终审操作，不可进行驳回!");
            }
            // 3. 状态机校验
            String currentStatus = shipHd.getShStatus();
            switch (currentStatus) {
                case "999":
                    return AjaxResult.error(" 物流残次单【" + rejectReportedVO.getBillId() + "】已终止，不可再进行驳回操作!");
                case "000":
                    return AjaxResult.error(" 物流残次单【" + rejectReportedVO.getBillId() + "】待确认，不可直接进行驳回操作!");
                case "001":
                    return AjaxResult.error("当前物流残次单【" + rejectReportedVO.getBillId() + "】还未被区域经理审核通过，当前流程还不允许你来进行驳回操作!");
                case "002":
                    return AjaxResult.error("当前物流残次单【" + rejectReportedVO.getBillId() + "】还未被物流审核通过，当前流程还不允许你来进行驳回操作!");
                case "003":
                    break;
                default:
                    return AjaxResult.error(" 物流残次单【" + rejectReportedVO.getBillId() + "】状态异常");
            }
            // 4. 执行审批
            int updated = wBlShipHdService.riskUpdateStatusByBillId(rejectReportedVO);

            if (updated > 0) {
                sendDingTalkMarkDown(rejectReportedVO, "运营部门(风控驳回)");
                return AjaxResult.success(" 物流残次单【" + rejectReportedVO.getBillId() + "】已经成功驳回!");
            }
            return AjaxResult.error(" 物流残次单审核操作未生效");
        } catch (Exception e) {
            return AjaxResult.error(" 系统处理异常: " + e.getMessage());
        }
    }


    /**
     * 风控审核通过
     *
     * @param requestVO
     * @return
     */
    @PutMapping("/riskApproveReported")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult riskApproveReportedByBillId(@RequestBody rejectReportedVO requestVO) {
        // 1. 参数校验
        if (StringUtils.isBlank(requestVO.getBillId())) {
            return AjaxResult.error(" 物流残次单号不能为空");
        }
        try {
            // 2. 获取单据信息
            wBlShipHd shipHd = wBlShipHdService.selectShipInfoByBillId(requestVO.getBillId());
            if (shipHd == null) {
                return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】不存在");
            }

            // 判断当前是哪种处理方式
            if (StringUtils.isNotBlank(requestVO.getType())) {
                if ("sendback".equals(requestVO.getType())) {
                    // 检查物流单号是否完善
                    if (StringUtils.isBlank(requestVO.getWlBillId()) || " ".equals(requestVO.getWlBillId())) {
                        return AjaxResult.error("当前物流残次的处理方式是寄回供应商，但是门店还未填写物流单号，请通知门店填写物流单号，你才能进行审核!");
                    }
                    if (StringUtils.isBlank(requestVO.getBffj()) && requestVO.getBffj().equals(' ')) {
                        return AjaxResult.error("门店还未上传提报物流商品的报废视频，请通知门店尽快上传残次视频，不允许进行审核!");
                    }
                } else if ("endvideo".equals(requestVO.getType())) {
                    if (StringUtils.isBlank(requestVO.getBffj()) || " ".equals(requestVO.getBffj())) {
                        return AjaxResult.error("门店还未上传提报物流商品的报废视频，请通知门店尽快上传残次视频，不允许进行审核!");
                    }

                }
            }
            if ("004".equals(shipHd.getStatus())) {
                return AjaxResult.error("当前物流残次单号【" + requestVO.getBillId() + "】已经完成终审操作，不可进行审核!");
            }
            // 3. 状态机校验
            String currentStatus = shipHd.getShStatus();
            switch (currentStatus) {

                case "999":
                    return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】已终止，不可审核");
                case "000":
                    return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】待确认，不可直接审核");
                case "001":
                    return AjaxResult.error("当前物流残次单【" + requestVO.getBillId() + "】还未被区域经理审核通过，当前流程还不允许你来进行审核操作!");
                case "002":
                    return AjaxResult.error("当前物流残次单【" + requestVO.getBillId() + "】还未被物流审核通过，当前流程还不允许你来进行驳回操作!");
                case "003":
                    break;
                default:
                    return AjaxResult.error(" 物流残次单【" + requestVO.getBillId() + "】状态异常");
            }
            // 4. 执行审批
            int updated = wBlShipHdService.riskApprovalStatusByBillId(requestVO);

            if (updated > 0) {
                // 通知店铺：
                List<dArcStaff> recipients = getRecipientStaffsToAll(requestVO);
                recipients.forEach(staff -> {
                    riskSendDingTalkMarkDown(requestVO, staff);
                });

                // 获取所有物流人员信息
                // 获取所有物流人员
                List<sysLoginUser> users = sysLoginUserService.selectAllLogisticsInfos();
                // 将钉钉工号使用逗号隔开
                // 使用Stream API处理
                String staffIds = users.stream()                       // 创建流
                        .map(sysLoginUser::getOldStaffId)                // 提取oldStaffId
                        .filter(id -> id != null && !id.isEmpty())        // 过滤掉null和空字符串
                        .collect(Collectors.joining(","));

                if (StringUtils.isNotBlank(staffIds)) {
                    riskSendDingTalkMarkDownWl(requestVO, staffIds);
                }
                // 审核通过之后 判断当前品类是否是盲盒
                // 如果是盲盒 那么就不更新
                wBlShipHdService.updateBfStatusByBillId(requestVO);
                asyncExecuteProcedures(requestVO.getBillId());  // 异步执行

                // 调用存储过程 两个一起调用
                // 审核通过之后将当前单号更新


                return AjaxResult.success(" 物流残次单【" + requestVO.getBillId() + "】审核通过");
            }

            return AjaxResult.error(" 物流残次单审核操作未生效");
        } catch (Exception e) {
            return AjaxResult.error(" 系统处理异常: " + e.getMessage());
        }
    }


    @Async("procExecutor")
    public void asyncExecuteProcedures(String billId) {
        storedProceduresService.adjustInventory(billId);
        storedProceduresService.deductSupplierPayment(billId);
    }

    // 驳回发送信息
    public void riskSendDingTalkMarkDown(rejectReportedVO reportedVO, dArcStaff staff) {
        CWeiXinConfigQy cobotConfig = getCobotConfig();

        // 构建Markdown内容（带动态进度图标）
        StringBuilder markdownBuilder = new StringBuilder()
                .append("### 🎉 物流残次商品报废流程全部结束\n\n")
                .append("🎁 **处理结果**\n")
                .append("- 🏬 门店: ").append(reportedVO.getStoreName()).append("\n")
                .append("- 👤 提报人: ").append(reportedVO.getStaffName()).append("\n\n")
                .append("- 📦 商品: ").append(reportedVO.getItemName()).append("\n")
                .append("- 📌 单据号: ").append(reportedVO.getBillId()).append("\n\n")

                // 修改重点：进度条带完成状态图标
                .append("⏳ **处理进度**\n")
                .append("1. 门店提报 ✅\n")  // 每条进度后加✅
                .append("2. 区域经理审核通过 ✅\n")
                .append("3. 物流审核通过 ✅\n")
                .append("4. 风控审核 ✅\n")
                .append("5. 报废流程全部结束 ✅\n\n")  // 最终步骤用庆祝图标

                .append("🔗 **相关入口**\n")
                .append("- [查看完整处理记录](").append(buildDetailUrl(reportedVO)).append(")\n");

        // 消息队列设置（保持不变）
        dingTalkMessageQueue queue = new dingTalkMessageQueue();
        queue.setMsgType("MARKDOWN");
        queue.setTitle("🎉  物流残次商品终审通过通知");
        queue.setRobotToken(cobotConfig.getAccessToken());
        queue.setRobotCode(cobotConfig.getAeskey());
        queue.setMarkdownContent(markdownBuilder.toString());
        queue.setUserIds(StringUtils.defaultIfBlank(staff.getOldStaffId(), "475410075935471898"));

        sendDingTalkMarkdownMessage(queue);
    }


    public void riskSendDingTalkMarkDownWl(rejectReportedVO reportedVO, String staffIds) {
        CWeiXinConfigQy cobotConfig = getCobotConfig();

        // 构建Markdown内容（带动态进度图标）
        StringBuilder markdownBuilder = new StringBuilder()
                .append("### 🎉 物流残次商品报废流程全部结束\n\n")
                .append("🎁 **处理结果**\n")
                .append("- 🏬 门店: ").append(reportedVO.getStoreName()).append("\n")
                .append("- 👤 提报人: ").append(reportedVO.getStaffName()).append("\n\n")
                .append("- 📦 商品: ").append(reportedVO.getItemName()).append("\n")
                .append("- 📌 单据号: ").append(reportedVO.getBillId()).append("\n\n")

                // 修改重点：进度条带完成状态图标
                .append("⏳ **处理进度**\n")
                .append("1. 门店提报 ✅\n")  // 每条进度后加✅
                .append("2. 区域经理审核通过 ✅\n")
                .append("3. 物流审核通过 ✅\n")
                .append("4. 风控审核 ✅\n")
                .append("5. 报废流程全部结束 ✅\n\n")  // 最终步骤用庆祝图标

                .append("🔗 **相关入口**\n")
                .append("- [查看完整处理记录](").append(buildDetailUrl(reportedVO)).append(")\n");

        // 消息队列设置（保持不变）
        dingTalkMessageQueue queue = new dingTalkMessageQueue();
        queue.setMsgType("MARKDOWN");
        queue.setTitle("🎉  物流残次商品终审通过通知");
        queue.setRobotToken(cobotConfig.getAccessToken());
        queue.setRobotCode(cobotConfig.getAeskey());
        queue.setMarkdownContent(markdownBuilder.toString());
        queue.setUserIds(staffIds);

        sendDingTalkMarkdownMessage(queue);
    }


    // 通过采购 发进群组
    private void sendCgToDingTalk(rejectReportedVO reportedVO) {
        // 构建Markdown内容（为每个信息项配上更合适的图标）
        StringBuilder markdownBuilder = new StringBuilder()
                // 头部状态标识（使用庆祝图标）
                .append("### 🎉 物流残次商品终审通过通知\n\n")

                // 门店信息部分
                // 核心信息区块（使用礼物图标强调完成状态）
                .append("🎁 **处理结果**\n")
                .append("- 🏬 门店: ").append(reportedVO.getStoreName()).append("\n")
                .append("- 📦 商品: ").append(reportedVO.getItemName()).append("\n")
                .append("- 👤 提报人: ").append(reportedVO.getStaffName()).append("\n\n")
                .append("- 📌 单据号: ").append(reportedVO.getBillId()).append("\n\n")

                // 流程时间轴（使用时钟图标）
                .append("⏳ **处理进度**\n")
                .append("1. 门店提报 ✅\n")  // 每条进度后加✅
                .append("2. 区域经理审核通过 ✅\n")
                .append("3. 物流审核通过 ✅\n")
                .append("4. 风控审核 ✅\n")
                .append("5. 终审通过 🎉\n\n")  // 最终步骤用庆祝图标
                .append("🔗 **相关入口**\n")
                .append("- [查看完整处理记录](").append(buildDetailUrl(reportedVO)).append(")\n");

        // 发送给采购人员
        dingTalkSendContent textContent = new dingTalkSendContent();
        textContent.setTextContent("🚨 物流残次商品提报通知");
        textContent.setChatId(noticeDingTalkChatId);
        int inserted = dingTalkSendContentService.insertTextContent(textContent);
        // 6. 发送给采购的Markdown通知
        if (inserted > 0) {
            dingTalkSendContent content = new dingTalkSendContent();
            content.setMarkdownContent(markdownBuilder.toString());
            content.setChatId(noticeDingTalkChatId);
            dingTalkSendContentService.insertMarkdownMessage(content);
        }
    }


    private String buildDetailUrl(rejectReportedVO vo) {
        return String.format("https://mms.mumuso.com:8214/index/#/risk/?billId=%s", vo.getBillId());
    }


    private List<dArcStaff> getRecipientStaffsToDouble(rejectReportedVO vo) {
        List<dArcStaff> staffs = new ArrayList<>();
        addStaffIfValid(staffs, vo.getAreaStaff(), dArcStaffService::selectDingUserIdByStaffId);
        addStaffIfValid(staffs, vo.getStaffId(), dArcStaffService::selectDingUserIdByStaffId);
        return staffs;
    }

    private List<dArcStaff> getRecipientStaffsToAll(rejectReportedVO vo) {
        List<dArcStaff> staffs = new ArrayList<>();
        addStaffIfValid(staffs, vo.getAreaStaff(), dArcStaffService::selectDingUserIdByStaffId);
        addStaffIfValid(staffs, vo.getStaffId(), dArcStaffService::selectDingUserIdByStaffId);
        return staffs;
    }

    private void buildCommonMsg(StringBuilder builder, rejectReportedVO vo) {
        builder.append("🏬  **门店名称:** ").append(vo.getStoreName()).append("\n\n")
                .append("📦 **商品名称:** ").append(vo.getItemName()).append("\n\n")
                .append("👤 **提报人:** ").append(vo.getStaffName()).append("\n\n");
    }

    public void sendOverruleMessage(rejectReportedVO reportedVO, String type) {
        // 参数校验
        if (!"endvideo".equals(type) && !"sendback".equals(type)) {
            throw new IllegalArgumentException("非法消息类型: " + type);
        }

        // 基础配置
        CWeiXinConfigQy cobotConfig = getCobotOperateConfig();
        dArcStaff dArcStaff = dArcStaffService.selectDingUserIdByStaffId(reportedVO.getStaffId());

        // 消息构建
        StringBuilder markdownBuilder = new StringBuilder();
        markdownBuilder.append("###  ⚠️ ")
                .append("endvideo".equals(type) ? "物流残次商品报废视频不合格提醒" : "物流残次商品物流单号与视频不合格提醒")
                .append("\n\n");

        // 公共信息
        buildCommonMsg(markdownBuilder, reportedVO);

        // 差异化内容
        if ("endvideo".equals(type)) {
            markdownBuilder.append("🎥  **视频状态:** 拍摄内容不符合要求，请重新拍摄\n\n")
                    .append("🔍 **不合格原因:** ").append(reportedVO.getScrapReason()).append("\n\n");
        } else {
            markdownBuilder.append("📦  **物流单号填写有误或包裹不合格原因:** ").append(reportedVO.getScrapReason()).append("\n\n");
        }

        // 动态链接
        String linkText = "endvideo".equals(type) ? "📲 立即重新拍摄" : "📱 重新上传包裹视频或修改物流单号";
        markdownBuilder.append("[")
                .append(linkText)
                .append("](")
                .append(generateVideoUploadDeepLink(reportedVO, type))
                .append(")\n\n");

        // 消息发送
        dingTalkMessageQueue queue = new dingTalkMessageQueue();
        queue.setMsgType("MARKDOWN");
        queue.setTitle("⚠️  " + ("endvideo".equals(type) ? "物流残次商品报废视频不合格重新拍摄提醒" : "物流残次商品物流单号或视频不合格提醒"));
        queue.setRobotToken(cobotConfig.getAccessToken());
        queue.setRobotCode(cobotConfig.getAeskey());
        queue.setMarkdownContent(markdownBuilder.toString());
        queue.setUserIds(StringUtils.isNotBlank(dArcStaff.getOldStaffId()) ? dArcStaff.getOldStaffId() : "475410075935471898");

        sendDingTalkMarkdownMessage(queue);
    }


    private String generateVideoUploadDeepLink(rejectReportedVO vo, String type) {
        StringBuilder messageUrl = new StringBuilder();
        if ("endvideo".equals(type)) {
            messageUrl.append("https://mms.mumuso.com:8214/index/#/shoot/?")
                    .append("billId=").append(vo.getBillId())
                    .toString();
        } else {
            messageUrl.append("https://mms.mumuso.com:8214/index/#/track/?")
                    .append("billId=").append(vo.getBillId())
                    .toString();
        }
        return messageUrl.toString();
    }


    @PutMapping("/rejectVideoOrWlInfo")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult rejectVideoOrWlBillId(@RequestBody rejectReportedVO reportedVO) {
        if (ObjectUtils.isEmpty(reportedVO)) {
            return AjaxResult.error("前端传递的对象不能为空!");
        }

        if ("004".equals(reportedVO.getStatus())) {
            return AjaxResult.error("当前物流残次单【" + reportedVO.getBillId() + "】你已经完成审核，不允许在驳回!");
        }

        // 其次判断当前残次类型 是报废视频的类型还是物流单号和拍摄包裹的视频
        if (StringUtils.isNotBlank(reportedVO.getType())) {
            // 判断当前类型是报废视频还是寄回供应商
            if ("endvideo".equals(reportedVO.getType())) {
                // 发送重新拍摄报废视频的链接给到门店
                // 报废视频不合格 重新上传报废视频
                // 发送给门店
                sendOverruleMessage(reportedVO, "endvideo");
                return AjaxResult.success("已经将当前物流残次单【" + reportedVO.getBillId() + "】的不合格报废视频发送给门店进行重新提报!");
            } else {
                sendOverruleMessage(reportedVO, "sendback");
                return AjaxResult.success("已经将当前物流残次单【" + reportedVO.getBillId() + "】的错误物流单号信息或者寄回包裹视频不合格发送给门店进行重新提报!");
            }
        } else {
            return AjaxResult.error("当前物流残次类型未被定义!");
        }
    }

}
